<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">{{ title }}</span>
        <el-button
          style="float: right"
          size="mini"
          type="primary"
          @click="() => handleSubmit()"
          >保存</el-button
        >
      </div>
      <div class="text item">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="basic">
            <el-form
              :model="user"
              :rules="rules"
              ref="userForm"
              label-width="80px"
              style="width: 70%"
            >
              <el-form-item :label="$t('common.name')" prop="userName">
                <el-input v-model="user.userName"></el-input>
              </el-form-item>
              <el-form-item :label="$t('common.email')" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item :label="$t('common.phone')" prop="phoneNumber">
                <el-input v-model="user.phoneNumber"></el-input>
              </el-form-item>
              <el-form-item label="部门" prop="departmentId">
                <department-select
                  :multiple="true"
                  v-model="user.extraProperties.DepartmentId"
                ></department-select>
              </el-form-item>
              <el-form-item
                :label="$t('common.role')"
                prop="roleNames"
                v-if="showRoleSelect"
              >
                <role-select
                  :multiple="true"
                  v-model="user.roleNames"
                  :roleIds.sync="user.roleIds"
                ></role-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane
            label="数据权限"
            name="datapermission"
            @tab-click="handleTabChange"
          >
            <el-row>
              <el-col>
                <el-checkbox v-model="dataPermission.isOwnDepartment"
                  >仅部门数据</el-checkbox
                ></el-col
              >
            </el-row>
            <el-row>
              <el-col>
                <el-checkbox v-model="dataPermission.isOwnCreated"
                  >仅本人创建</el-checkbox
                ></el-col
              >
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>
<script>
import roleSelect from "@/components/Select/roleSelect";
import departmentSelect from "@/components/Select/departmentSelect.vue";
import {
  getUser,
  getUserRoles,
  addUser,
  updateUser,
  getUserDataPermission,
} from "@/api/user";
export default {
  components: {
    roleSelect,
    departmentSelect,
  },
  data() {
    return {
      user: {
        userName: "",
        email: "",
        phoneNumber: "",
        roleNames: [],
        roleIds: [],
        extraProperties: {
          DepartmentId: null,
        },
      },
      rules: {
        userName: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        roleNames: [
          {
            validator: this.roleValidator,
            trigger: "blur",
          },
        ],
      },
      showRoleSelect: false,
      title: "",
      activeName: "basic",
      dataPermission: {
        isOwnDepartment: false,
        isOwnCreated: false,
      },
    };
  },
  methods: {
    getUserData() {
      if (!this.userId) {
        this.showRoleSelect = true;
        return;
      }
      getUser(this.userId).then((res) => {
        this.user = res || {};
        this.user.roleIds = [];
        this.getUserRoles();
        this.getUserDataPermission();
      });
    },
    getUserRoles() {
      if (!this.userId) {
        this.showRoleSelect = true;
        return;
      }
      getUserRoles(this.userId).then((res) => {
        let roles = res ? res.items : [];
        this.user.roleNames = roles.map((role) => {
          return role.name;
        });
        this.user.roleIds = roles.map((role) => {
          return role.id;
        });
        this.showRoleSelect = true;
      });
    },
    getUserDataPermission() {
      if (!this.userId) return;

      getUserDataPermission(this.userId).then((res) => {
        this.dataPermission = res || {};
      });
    },
    handleSubmit() {
      this.$refs["userForm"].validate((valid) => {
        if (valid) {
          this.saveData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveData() {
      this.user.extraProperties.DataPermission = {
        IsOwnDepartment: this.dataPermission.isOwnDepartment,
        IsOwnCreated: this.dataPermission.isOwnCreated,
      };
      if (!this.userId) {
        this.user.password = "1q2w3E*";
        addUser(this.user).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      } else {
        updateUser(this.user).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      }
    },
    roleValidator(rule, value, callback) {
      if (!this.user.roleNames || this.user.roleNames.length == 0) {
        let tips = this.$t("tips.requireItem");
        callback(new Error(tips));
      } else callback();
    },
    handleCancel() {
      this.$emit("close");
    },
    handleTabChange(name) {
      if (name == "datapermission") {
      }
    },
  },
  created() {
    this.getUserData();
  },
  mounted() {
    this.title = this.id ? "编辑" : "新增";
  },
  computed: {
    userId() {
      return this.id || "";
    },
  },
  watch: {},
  props: {
    id: {
      type: String,
      default: null,
    },
  },
};
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
